package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikesBehaviorServiceImpl implements IApUnlikesBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存不喜欢行为记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveUnlikes(UnLikesBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();
        //构建不喜欢行为表对象
        ApUnlikesBehavior unlikesBehavior = new ApUnlikesBehavior();
        if (user != null){
            unlikesBehavior.setUserId(user.getUserId());
        }else {
            unlikesBehavior.setEquipmentId(dto.getEquipmentId());
        }
        unlikesBehavior.setArticleId(dto.getArticleId());
        unlikesBehavior.setType(dto.getType());
        unlikesBehavior.setCreatedTime(new Date());
        //查询该用户是否有过对该文章该行为的操作记录
        Query query = new Query();
        if (user == null){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);

        if (one == null){
            //无记录
            mongoTemplate.save(unlikesBehavior);
        }else {
            //有记录
            if (one.getType() != dto.getType()){
                Update update = new Update();
                update.set("type",dto.getType());
                mongoTemplate.updateFirst(query,update,ApUnlikesBehavior.class);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 查询不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {
        Query query =new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() == null){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }

        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }
}
